/**
 * 国内市场指数数据钩子
 */

import { useQuery } from '@tanstack/react-query';
import { get } from '@shared/utils/apiClient';
import { ApiResponse, IndexData } from '@shared/types/market';
import { getRefreshInterval } from '@shared/utils/marketStatus';

const API_BASE = import.meta.env.VITE_API_BASE_URL || '';

/**
 * 获取多个国内指数数据
 */
export function useMarketIndexes(codes?: string[]) {
  return useQuery({
    queryKey: ['marketIndexes', codes],
    queryFn: async () => {
      const params = codes ? `?codes=${codes.join(',')}` : '';
      const response = await get<ApiResponse<IndexData[]>>(
        `${API_BASE}/api/v1/market/indexes${params}`
      );
      return response.data;
    },
    refetchInterval: getRefreshInterval(), // 动态刷新间隔
    staleTime: 15000, // 15秒内认为数据新鲜
    gcTime: 60000, // 缓存1分钟
    refetchOnWindowFocus: false, // 窗口聚焦不刷新
  });
}

/**
 * 获取单个指数数据
 */
export function useIndexData(code: string) {
  return useQuery({
    queryKey: ['indexData', code],
    queryFn: async () => {
      const response = await get<ApiResponse<IndexData>>(
        `${API_BASE}/api/v1/market/index?code=${code}`
      );
      return response.data;
    },
    refetchInterval: getRefreshInterval(),
    staleTime: 15000,
    gcTime: 60000,
    refetchOnWindowFocus: false,
    enabled: !!code, // 只有当code存在时才启用
  });
}

